package io.geekidea.boot.headquarters.controller;


import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import io.geekidea.boot.common.PageDto;
import io.geekidea.boot.framework.response.ApiResult;
import io.geekidea.boot.headquarters.dto.HeadquartersDto;
import io.geekidea.boot.headquarters.dto.HeadquartersExcel;
import io.geekidea.boot.headquarters.entity.Headquarters;
import io.geekidea.boot.headquarters.query.HeadquartersQuery;
import io.geekidea.boot.headquarters.service.HeadquartersService;
import io.geekidea.boot.outbound.dto.OutboundExcel;
import io.geekidea.boot.outbound.query.OutboundQuery;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.math3.ml.neuralnet.UpdateAction;


import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/headquarters")
@Tag(name="总部物料管理")
public class HeadquartersController {
    @Resource
    private HeadquartersService headquartersService;

    @PostMapping("/search")
    @Operation(summary = "搜索总部物料库",description = "按照多条件组合分页查询总部物料数据列表")
    public ApiResult search(@RequestBody HeadquartersQuery headquarters){
        Page<Headquarters> page=new Page<>(headquarters.getPage(),headquarters.getSize());
        Page<Headquarters> pageDto = headquartersService.headquartersPage(page, headquarters);
        PageDto<Headquarters> pageInfo=new PageDto<>(pageDto.getRecords(),pageDto.getTotal(),pageDto.getSize(),pageDto.getCurrent());
        return ApiResult.success(pageInfo);
    }

    @GetMapping("/get/{id}")
    @Operation(summary = "根据ID查询单条数据")
    public ApiResult getAreaById(@PathVariable(value = "id")Integer id){
        Headquarters headquarters=headquartersService.getById(id);
        return ApiResult.success(headquarters);
    }

//
    @DeleteMapping("/romove/{id}")
    @Operation(summary = "逻辑删除")
    public ApiResult removeArea(@PathVariable(value = "id")Integer id){
        headquartersService.removeById(id);
        return ApiResult.success("删除总部物料库成功！");
    }
//
    @PostMapping("/add")
    public ApiResult addHeadquarters(@RequestBody HeadquartersDto headquartersDto){
        Headquarters headquartersEntity=new Headquarters();
        BeanUtil.copyProperties(headquartersDto,headquartersEntity);
        headquartersService.save(headquartersEntity);
        return ApiResult.success("添加总部物料库成功！");
    }

    //物理删除
    @GetMapping("/del/{id}")
    @Operation(summary = "物理删除",description = "根据id物理删除")
    public ApiResult del(@PathVariable Integer id){
        int count = headquartersService.delById(id);
        if (count<0) {
            return ApiResult.success("删除失败");
        }
        return ApiResult.success("删除成功");

    }

    @PostMapping("/update")
    public ApiResult updateHeadquarters(@RequestBody HeadquartersDto headquartersDto){
        Headquarters headquartersEntity=new Headquarters();
        BeanUtil.copyProperties(headquartersDto,headquartersEntity);
        headquartersService.updateById(headquartersEntity);
        return ApiResult.success("更改总部物料库成功！");
    }



    @PostMapping("/list")
    @Operation(summary = "查询总部物料库基础数据")
    public ApiResult headquartersList(){
        List<Headquarters> headquartersList = headquartersService.list();
        return ApiResult.success(headquartersList);
    }

    @GetMapping("/getHeadquartersId/{id}")
    @Operation(summary = "根据ID查询单条数据")
    public ApiResult getHeadquartersId(@PathVariable(value = "id")Integer id){
        Headquarters headquarters=headquartersService.getHeadquartersId(id);
        return ApiResult.success(headquarters);
    }

    @PostMapping("/download")
    @Operation(tags = "Post",description = "下载文件")
    public void download(@RequestBody HeadquartersQuery headquartersQuery, HttpServletResponse response){
        List<HeadquartersExcel> list = headquartersService.getDownloadList(headquartersQuery);
        OutputStream outputStream = null;
        try {
            response.setCharacterEncoding("UTF-8");
            String excelName = URLEncoder.encode("headquartersentry_"+ LocalDateTime.now(), "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + excelName + ".xlsx");
            // 以字节流的形式输出响应正文
            outputStream = response.getOutputStream();
            try (ExcelWriter excelWriter = EasyExcel.write(outputStream, HeadquartersExcel.class).build()) {
                WriteSheet writeSheet = EasyExcel.writerSheet(0).build();
                excelWriter.write(list,writeSheet);
            }
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }
        }
    }
}
